import React, { memo, useCallback, useEffect, useState } from 'react'
import { shallowEqual, useDispatch, useSelector } from 'react-redux'
import {
  PlaylistWrapper,
  NavWrapper,
  ContentWrapper
} from './style'
import {
  getPlaylistAction,
  getCurrentPageAction,
  getPlaylistCatAction
} from './store/actionCreators'
import {
  formatImg,
  formatCount
} from '@/utils/format'
import { Pagination } from 'antd'
import Category from './c-cpns/category'
import useShowPlaylistDetail from '@/hooks/useShowPlaylistDetail'

export default memo(function Playlist() {
  const dispatch = useDispatch()
  useEffect(() => {
    dispatch(getPlaylistAction())
    dispatch(getPlaylistCatAction())
  }, [dispatch])
  const { playlist,totalCount,currentPage,currentCat} = useSelector(state => ({
    playlist: state.getIn(['playlist', 'playlist']),
    totalCount: state.getIn(['playlist', 'totalCount']),
    currentPage: state.getIn(['playlist', 'currentPage']),
    currentCat:state.getIn(['playlist','currentCat'])
  }), shallowEqual)
  const changePage = useCallback((page,pageSize) => {
    dispatch(getCurrentPageAction(page))
    dispatch(getPlaylistAction())
  }, [dispatch])
  const goToPlaylistDetail = useShowPlaylistDetail()

  const [isShowCat, setIsShowCat] = useState(false)
  const showCate = () => {
    setIsShowCat(!isShowCat)
  }
  const playlists = playlist || []
  return (
    <PlaylistWrapper className="wrap-v2">
      <NavWrapper>
        <div className='cat'>{currentCat}</div>
        <div className='choose' onClick={e => showCate()}>选择分类</div>
        {
          isShowCat ? <Category showCate={showCate}/> : null
        }
        <div className='hot'>热门</div>
      </NavWrapper>
      <ContentWrapper>
        {
          playlists.map(item => {
            return (
              <div key={item.id} className='item'>
                <div className="mask sprite_covor" onClick={e => goToPlaylistDetail(item.id)}></div>
                <img src={formatImg(item.coverImgUrl, 140)} alt="" />
                <div className="desc">
                  <i className="sprite_icon erji"></i>
                  <span className='count'>{formatCount(item.playCount)}</span>
                  <i className="sprite_icon play"></i>
                </div>
                <div className="name text-nowrap" onClick={e => goToPlaylistDetail(item.id)}>{item.name}</div>
                <div className="creator">
                  <span>by {item.creator.nickname}</span>
                  {item.creator.avatarDetail? <img src={item.creator.avatarDetail.identityIconUrl} alt="" className='icon' /> : null}
                </div>
              </div>
            )
          })
        }
      </ContentWrapper>
      <Pagination
        current={currentPage}
        total={totalCount}
        showSizeChanger={false}
        pageSize={35}
        onChange={changePage}
      className='pagination'/>
    </PlaylistWrapper>
  )
})
